<template>
	<view class="content">
		<view :style="{marginTop: parseInt($statusHeight + 20) + 'rpx'}"></view>
		<image class="logo" src="/static/logo.png"></image>
		<button class="top" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
			@tap="handleUserInfo">小程序手机快捷登录</button>
			<navbar titleText="个人信息" />
	</view>
</template>

<script setup>
	import {
		useMineStore
	} from '@/stores/modules/mine'
	import {
		storeToRefs
	} from 'pinia'
	import {
		ref,
		onMounted,
		reactive
	} from 'vue'
	import {
		postLogin
	} from '@/api/login.js'

	//创建仓库对象
	const mineStore = useMineStore()
	const {
		userInfo
	} = storeToRefs(mineStore)
	//拿到userInfo可以直接用userInfo.value，例如const res = await updategender({userId: userInfo.value.id})

	let submit = () => {
		let res = await postLogin({
			tel: tel,
			code: code
		})
	}
	
	
	let userList = reactive({
		code:'',
		iv: '',
		encryptedData: '',
		nickname: '',
		avatar: ''
	})
	
	const handleOauther = async () => {
		uni.login({
			provider: 'weixin', //使用微信登录
			success: function(res) {
				userList.code = res.code;
			},
			fail: error => {
				uni.showToast({
					icon: 'none',
					title: '登录失败'
				})
				close()
			},
			complete: () => {
				
			}
		})
	}
	
	//获取code
	onMounted(() => {
		handleOauther();
	})
	
	const handleUserInfo = () => {
		uni.getUserProfile({
			desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: (res) => {
				userList.avatar=res.avatarUrl;
				userList.nickname=res.nickname;
			}
		})
	
	}
	
	// 手机号授权回调方法
	const getPhoneNumber = (e) => {
		if (e.detail.iv) {
			// 因为微信对手机号码的安全性做的很好，所以这里只能获取到加密后的数据，还需要拿到后端解密
			userList.iv = e.detail.iv
			userList.encryptedData = e.detail.encryptedData
	
			// 手机号授权是后执行的，所以授权成功后直接调用授权登录接口将this.loginModel传入
			// 这里简化了代码直接发送http请求，而不是通过vuex的方法进行请求，因为后者能够将后端返回的数据进行存储比如token，userInfo等
			uni.request({
				url: '',
				method: 'POST',
				data: userList,
				success: (res) => {
					mineStore.saveUserInfo({
						token: res.data.data.userInfo.token,
						userInfo: res.data.data.userInfo
					})
					uni.showToast({
						icon: 'none',
						title: '登录成功'
					})
					uni.switchTab({
						url: '/pages/index/index'
					})
				}
			})
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>